import { ElMessageBox } from "element-plus";
import { tr } from "element-plus/es/locale";
import saveAs from "file-saver";
import JSZip from "jszip";
import { defineStore } from "pinia";
import router from "../router";

export const useBlog = defineStore("useBlog", {
  persist: {
    key: "yyqs-blog",
    storage: sessionStorage,
    paths: ["article"],
  },
  state: () => {
    return {
      article: {
        articles: [
          {
            id: 1,
            title: "标题1",
            author: "一叶千生",
            isTitleEdit: false,
            isAuthorEdit: false,
            content: "文章内容",
            contentForm: "文章内容",
            type: true, //是否原创文章
            isPublish: false,
            isTop: true,
            createDateTime: "2022/8/12",
            publishDateTime: "2022/8/12",
            saveDateTime: "2022/9/13",
            tags: [0, 1, ""], //记录标签的下标,-1作为添加留空
          },
          {
            id: 2,
            title: "标题2",
            author: "一叶千生",
            isTitleEdit: false,
            isAuthorEdit: false,
            content: "文章内容2",
            contentForm: "文章内容2",
            type: true, //是否原创文章
            isPublish: false,
            isTop: true,
            createDateTime: "2022/8/12",
            publishDateTime: "2022/8/12",
            saveDateTime: "2022/9/13",
            tags: [0, ""], //记录标签的下标,-1作为添加留空
          },
        ] as any,
        articlesForm: {
          id: 0,
          title: "",
          author: "",
          isTitleEdit: true,
          isAuthorEdit: true,
          content: "",
          contentForm: "",
          type: true, //是否原创文章
          isPublish: false,
          isTop: true,
          createDateTime: "",
          publishDateTime: "",
          saveDateTime: "",
          tags: [""], //记录标签的下标,-1作为添加留空
        } as any,
        tags: ["编程", "计算机"], //全部标签值
        selection: [] as number[],
        isTabInputDisplay: false,
        expandRows: [] as number[],
        articleTab: 1, //激活标签页
        articlesTabs: [] as number[], //编辑器标签页
        articleFileList: [] as any, //导入文件列表
        filter: { type: -1, isPublish: -1 }, //过滤选项
      },
    };
  },
  getters: {
    getArticlesContent: (state) => {
      return state.article.articles.filter((v: any) => {
        return state.article.articlesTabs.includes(v.id);
      });
    },
    getIndex: (state) => {
      return (id: number) => {
        return state.article.articles.findIndex((v: any) => v.id == id);
      };
    },
    getArticlesFilter: (state) => {
      return () => {
        if (
          state.article.filter.type == -1 &&
          state.article.filter.isPublish == -1
        )
          return state.article.articles;

        return state.article.articles
          .filter((v: { type: number }) => {
            if (state.article.filter.type != -1) {
              //true返回原创结果
              return state.article.filter.type == 0 ? v.type : !v.type;
            }
            return true;
          })
          .filter((v: { isPublish: number }) => {
            if (state.article.filter.isPublish != -1) {
              //true返回原创结果
              return state.article.filter.isPublish == 0
                ? v.isPublish
                : !v.isPublish;
            }
            return true;
          });
      };
    },
  },
  actions: {
    //文章置顶
    setTop(type: boolean) {
      ElMessage({
        message: type ? "已置顶" : "取消置顶",
        type: type ? "success" : "info",
        duration: 500,
      });
    },
    //文章删除
    articlesDelete(type: number, id = 0) {
      type == 1
        ? ElMessageBox.confirm("是否删除选中的全部文章", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            showClose: false,
            type: "error",
          })
            .then(() => {
              for (let item of this.article.selection) {
                let index = this.article.articles.findIndex(
                  (v: any) => v.id == item
                );
                this.article.articles.splice(index, 1);
              }
              ElMessage({
                type: "success",
                message: "成功删除！",
                duration: 500,
              });
            })
            .catch(() => {
              ElMessage({
                type: "info",
                message: "取消删除！",
                duration: 500,
              });
            })
        : (() => {
            ElMessageBox.confirm("是否删除该文章", {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              showClose: false,
              type: "error",
            })
              .then(() => {
                let index = this.article.articles.findIndex(
                  (v: any) => v.id == id
                );
                this.article.articles.splice(index, 1);
                ElMessage({
                  type: "success",
                  message: "成功删除！",
                  duration: 500,
                });
              })
              .catch(() => {
                ElMessage({
                  type: "info",
                  message: "取消删除！",
                  duration: 500,
                });
              });
          })();
    },
    //新建文章
    articleAdd() {
      const data = new Date();
      this.article.articlesForm.id = data.getTime();
      this.article.articlesForm.createDateTime = data.toLocaleString();

      this.article.articles.push(
        JSON.parse(JSON.stringify(this.article.articlesForm))
      );
      this.article.articlesForm = {
        id: 0,
        title: "",
        author: "",
        isTitleEdit: false,
        isAuthorEdit: false,
        content: "",
        contentForm: "",
        type: true, //是否原创文章
        isPublish: false,
        isTop: true,
        createDateTime: "",
        publishDateTime: "",
        saveDateTime: "",
        tags: [""],
      };
    },
    //文章内容编辑
    articleContentEdit(id: number) {
      //添加到编辑器的标签栏
      if (!this.article.articlesTabs.includes(id))
        this.article.articlesTabs.push(id);
      this.article.articleTab = id;

      //将内容赋给独立的表单，防止数据错乱
      let index = this.getIndex(id);
      console.log(this.article.articles[index]);
      this.article.articles[index].contentForm = JSON.parse(
        JSON.stringify(this.article.articles[index].content)
      );
      //跳转
      router.push("/blog/markdown");
    },
    //表格内编辑
    artitcHeaderEdit(row: any, column: any, cell: any, event: Event) {
      if (column.property == "title") row.isTitleEdit = true;
      else if (column.property == "author") row.isAuthorEdit = true;
    },
    //文章标签添加
    addTag(row: any) {
      this.article.isTabInputDisplay = false;
      let tag = JSON.parse(JSON.stringify(row.tags[row.tags.length - 1]));

      if (tag == "") return;

      this.article.tags.includes(tag)
        ? (() => {
            //在全部标签中的下标
            let index = this.article.tags.findIndex((v: string) => v == tag);

            //获取相同值的下标，去除重复
            let i = row.tags.findIndex((v: number) => v == index);
            if (i > -1) row.tags.splice(i, 1);

            row.tags[row.tags.length - 1] = index;
          })()
        : (() => {
            row.tags[row.tags.length - 1] = this.article.tags.length;

            this.article.tags.push(tag);
          })();
      row.tags.push("");
    },
    //文章标签删除
    deleteTag(row: any, index: number) {
      row.tags.splice(row.tags.indexOf(index), 1);
    },
    //表格展开项控制
    artitcleExpandChange(row: any) {
      let index = this.article.expandRows.indexOf(row.id);
      index > -1
        ? this.article.expandRows.splice(index, 1)
        : this.article.expandRows.push(row.id);
    },
    //编辑器标签移除
    articleTabRemove(name: number) {
      this.article.articles[this.getIndex(name)].contentForm = "";
      this.article.articlesTabs.splice(
        this.article.articlesTabs.indexOf(name),
        1
      );
    },

    //导出数据
    exportFile(type: number) {
      let blob: Blob;
      switch (type) {
        case 1:
          blob = new Blob([JSON.stringify(this.article.articles)], {
            type: "text/plain;charset=utf-8",
          });
          saveAs(blob, "全部文章.json");
          break;
        case 2:
          let result = this.article.articles.filter((v: { id: number }) => {
            return this.article.selection.includes(v.id);
          });
          blob = new Blob([JSON.stringify(result)], {
            type: "text/plain;charset=utf-8",
          });
          saveAs(blob, "部分文章.json");
          break;
        case 3:
          let zip = new JSZip();
          let md = zip.folder("")!;
          this.article.selection.forEach((v) => {
            blob = new Blob(
              [JSON.stringify(this.article.articles[this.getIndex(v)].content)],
              {
                type: "text/plain;charset=utf-8",
              }
            );
            md.file(
              `${this.article.articles[this.getIndex(v)].author}--${
                this.article.articles[this.getIndex(v)].title
              }.md`,
              blob
            );
          });
          zip
            .generateAsync({ type: "blob" }) // zip下载
            .then((content) => {
              saveAs(content, "文章内容.zip");
            });

          break;
        default:
          break;
      }
    },
  },
});
